// pages/teacher/kaoqin/faqi/faqi.js
const app = getApp();

Page({
  data: {
    courseId: null,
    courseList: [],
    selectedCourse: null,
    attendanceTypes: ['定位签到', '手势签到', '二维码签到'],
    attendanceTypeIndex: 0,
    validTime: 5, // 默认有效时间5分钟
    validTimeOptions: [5, 10, 15, 20, 30],
    validTimeIndex: 0,
    location: null,
    isCreating: false,
    isLoading: true
  },

  onLoad: function(options) {
    if (options.courseId) {
      this.setData({
        courseId: options.courseId
      });
    }
    
    this.fetchCourseList();
  },
  
  // 获取课程列表
  fetchCourseList: function() {
    this.setData({ isLoading: true });
    
    const userInfo = wx.getStorageSync('userInfo');
    
    wx.request({
      url: `${app.globalData.serverUrl || 'http://localhost:3000'}/api/teacher/courses`,
      method: 'GET',
      data: {
        userId: userInfo.userId
      },
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.success) {
          const courseList = res.data.data || [];
          
          this.setData({
            courseList: courseList,
            isLoading: false
          });
          
          // 如果有传入的课程ID，则自动选择该课程
          if (this.data.courseId) {
            const selectedCourse = courseList.find(course => course.courseId == this.data.courseId);
            if (selectedCourse) {
              this.setData({
                selectedCourse: selectedCourse
              });
            }
          }
        } else {
          wx.showToast({
            title: '获取课程列表失败',
            icon: 'none'
          });
          this.setData({ isLoading: false });
        }
      },
      fail: (err) => {
        console.error('获取课程列表失败:', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
        this.setData({ isLoading: false });
      }
    });
  },
  
  // 选择课程
  selectCourse: function(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      selectedCourse: this.data.courseList[index]
    });
  },
  
  // 选择考勤类型
  changeAttendanceType: function(e) {
    this.setData({
      attendanceTypeIndex: e.detail.value
    });
  },
  
  // 选择有效时间
  changeValidTime: function(e) {
    this.setData({
      validTimeIndex: e.detail.value,
      validTime: this.data.validTimeOptions[e.detail.value]
    });
  },
  
  // 获取当前位置
  getLocation: function() {
    wx.showLoading({
      title: '获取位置中...',
    });
    
    // 使用腾讯地图IP定位API
    wx.request({
      url: 'https://apis.map.qq.com/ws/location/v1/ip',
      data: {
        key: 'E7IBZ-FOSW3-H6Z3U-OG4X4-CWTDH-QNBV4'
      },
      success: (res) => {
        if (res.data.status === 0 && res.data.result && res.data.result.location) {
          const location = res.data.result.location;
          
          this.setData({
            location: {
              latitude: location.lat,
              longitude: location.lng,
              name: '正在获取地址...'
            }
          });
          
          // 添加2秒延迟后再获取位置名称
          setTimeout(() => {
            this.getLocationName(location.lat, location.lng);
          }, 2000);
        } else {
          wx.hideLoading();
          wx.showModal({
            title: '提示',
            content: '获取位置失败，请稍后重试',
            showCancel: false
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '网络请求失败，请检查网络连接',
          showCancel: false
        });
      }
    });
  },
  
  // 获取位置名称
  getLocationName: function(latitude, longitude) {
    wx.request({
      url: 'https://apis.map.qq.com/ws/geocoder/v1/',
      data: {
        location: `${latitude},${longitude}`,
        key: 'E7IBZ-FOSW3-H6Z3U-OG4X4-CWTDH-QNBV4',
        get_poi: 1,
        poi_options: 'policy=2;radius=1000' // 使用policy=2，这是到家场景，会细化到楼栋
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data.status === 0 && res.data.result) {
          const locationData = this.data.location;
          const addressInfo = res.data.result;
          
          // 直接使用完整地址
          let formattedAddress = '';
          if (addressInfo.formatted_addresses && addressInfo.formatted_addresses.standard_address) {
            formattedAddress = addressInfo.formatted_addresses.standard_address;
          } else if (addressInfo.address) {
            formattedAddress = addressInfo.address;
          } else {
            // 如果没有格式化地址，则自行拼接
            const component = addressInfo.address_component;
            formattedAddress = `${component.province}${component.city}${component.district}${component.street || ''}${component.street_number || ''}`;
          }
          
          // 不再创建简短地址，直接使用完整地址
          locationData.name = formattedAddress;
          
          // 保存更多位置信息
          if (addressInfo.ad_info) {
            locationData.adcode = addressInfo.ad_info.adcode;
            locationData.city = addressInfo.ad_info.city;
            locationData.district = addressInfo.ad_info.district;
          }
          
          this.setData({
            location: locationData
          });
        } else {
          const locationData = this.data.location;
          locationData.name = '未知地点';
          this.setData({
            location: locationData
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        const locationData = this.data.location;
        locationData.name = '未知地点';
        this.setData({
          location: locationData
        });
      }
    });
  },
  
  // 创建考勤
  createAttendance: function() {
    // 验证表单
    if (!this.data.selectedCourse) {
      wx.showToast({
        title: '请选择课程',
        icon: 'none'
      });
      return;
    }
    
    if (this.data.attendanceTypeIndex === 0 && !this.data.location) {
      wx.showToast({
        title: '请获取位置信息',
        icon: 'none'
      });
      return;
    }
    
    this.setData({
      isCreating: true
    });
    
    wx.showLoading({
      title: '创建考勤中...',
    });
    
    const userInfo = wx.getStorageSync('userInfo');
    
    // 准备请求数据
    const requestData = {
      userId: userInfo.userId,
      courseId: this.data.selectedCourse.courseId,
      classId: this.data.selectedCourse.classId,
      locationRequired: this.data.attendanceTypeIndex === 0, // 定位签到需要位置
      validDistance: 100, // 默认有效距离100米
      location: this.data.attendanceTypeIndex === 0 ? {
        latitude: this.data.location.latitude,
        longitude: this.data.location.longitude,
        address: this.data.location.name
      } : null
    };
    
    // 发送请求创建考勤
    wx.request({
      url: `${app.globalData.serverUrl || 'http://localhost:3000'}/api/teacher/start-session`,
      method: 'POST',
      data: requestData,
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token'),
        'Content-Type': 'application/json'
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.statusCode === 201) {
          wx.showModal({
            title: '创建成功',
            content: '考勤已创建，学生可以开始签到',
            showCancel: false,
            success: () => {
              // 返回考勤管理页面
              wx.navigateBack();
            }
          });
        } else {
          wx.showToast({
            title: res.data.message || '创建考勤失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('创建考勤失败:', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      },
      complete: () => {
        this.setData({
          isCreating: false
        });
      }
    });
  },
  
  // 显示完整地址
  showFullAddress: function() {
    if (this.data.location && this.data.location.name) {
      wx.showModal({
        title: '完整地址',
        content: this.data.location.name,
        showCancel: false
      });
    }
  }
});